package com.easy_buy.controller;

import com.github.pagehelper.*;

import com.easy_buy.component.Receiver;
import com.easy_buy.core.Result;
import com.easy_buy.domain.*;
import com.easy_buy.mapper.StoreMapper;
import com.easy_buy.repository.*;
import com.easy_buy.service.*;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.*;
import java.nio.charset.StandardCharsets;

@Controller
@RequestMapping("/store")
public class StoreController {
    @Autowired(required = false)
    private StoreMapper mapper;
    @Autowired
    private CheckService checkService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AopService aopService;
    @Autowired
    private ComRepository comRepository;
    @Autowired
    private ImgRepository imgRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private PreShopRepository preShopRepository;

    @Autowired
    private Receiver receiver;    // 消息队列

    // 全局参数
    private List<Category> categoryList;
    private List<Preshop> preshopList;
    private List<Preshop> cfmShopList;
    private PageInfo<Commodity> info;
    private String tid;
    private Result result;
    private String picname;
    private Commodity commodity;
    private User user;
    //商品图片资源加载器
    private ResourceLoader loader;

    @Autowired(required = false)
    @SuppressWarnings("all")
    public StoreController(ResourceLoader loader) {
        this.loader = loader;
    }

    @Value("${web.upload-path}")
    private String uploadpath;   //商品图片上传到的目录

    @Bean
    public Queue myQueue() {
        return new Queue("买家留言");
    }


    // 首页
    @GetMapping("/")     // tid是商品的大类信息
    public String init(Model model, @RequestParam(value = "tid", defaultValue = "") String id,
                       @RequestParam(value = "start", defaultValue = "0") int start,
                       @RequestParam(value = "size", defaultValue = "2") int size) throws Exception {
        //加载所有分类
        categoryList = mapper.getTypes();
        model.addAttribute("categorys", categoryList);

        //加载推荐商品
        PageHelper.startPage(start, size, "Pid DESC");//这一句必须写在接口调用之前
        List<Commodity> commodityList = new ArrayList<>();

        // 等于空字符串，表查询所有类别
        if (id.equals("")) {
            commodityList = mapper.queryComsAll();
        } else {    // 表示查询某一个类别
            commodityList = mapper.queryComsByTid(id);
        }
        // 放进分页器中
        info = new PageInfo<>(commodityList);
        model.addAttribute("page", info);
        tid = id;
        model.addAttribute("tid", tid);

        //加载Result响应实体
        if (result == null) {
            // 初始化
            result = new Result();
            result.setCode(100);
            result.setMsg("初始状态");
            result.setData(new Anonymous());
        }
        model.addAttribute("result", result);

        return "index";
    }

    // 显示图片
    @RequestMapping("/getpic")
    public ResponseEntity getPicture(int pid) {
        ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
        return builder.body(mapper.queryImgByPid(pid).getImage());
    }

    // 跳转到首页
    @GetMapping("/index")
    public String toIndex(Model model) {//这个方法是必须的,页面链接通过它来定向到首页
        model.addAttribute("categorys", categoryList);
        model.addAttribute("page", info);
        model.addAttribute("tid", tid);
        model.addAttribute("result", result);
        return "index";
    }


    // 跳转到登录页
    @GetMapping("/login")
    public String toLogin(Model model) {//这个方法是必须的,页面链接通过它来定向到登录页
        model.addAttribute("result", result);
        return "login";
    }

    // 登录验证
    @RequestMapping("/check")
    public String loginCheck(Model model, String code, String password) {
        result = checkService.check(code, password);
        model.addAttribute("result", result);
        if (result.getCode() == 200) {
            model.addAttribute("categorys", categoryList);
            model.addAttribute("page", info);
            model.addAttribute("tid", tid);
            if (result.getData().getRole().equals("顾客")) {
                aopService.activateUser((User) result.getData());
            }
            return "index";
        } else {
            return "login";
        }
    }

    // 注册
    @GetMapping("/register")
    public String toRegister(Model model) {//这个方法是必须的,页面链接通过它来定向到注册页
//        System.out.println(result);
        // 一开始result是初始状态， code=100
        model.addAttribute("result", result);
        //为表单录入初始模型
        user = new User();
        model.addAttribute("usr", user);
        return "register";
    }

    // 注册保存账号
    @RequestMapping(value = "/enrol", method = RequestMethod.POST)
    public String registerEnrol(Model model, @ModelAttribute("usr") @Validated User usr, BindingResult bindingResult) {
        // 结果无错误，返回首页
        if (!bindingResult.hasErrors()) {
            usr.setLogintime(new Date());
            user = usr;
            // 保存账号
            userRepository.save(usr);
            // 保存后同时登录
            result = checkService.check(usr.getCode(), usr.getPassword());
            // 这里网站一定要先从首页进来，再点注册，否则直接注册会有bug，有些数据没有，就会报错
            model.addAttribute("result", result);
            model.addAttribute("categorys", categoryList);
            model.addAttribute("page", info);
            model.addAttribute("tid", tid);
            return "index";
        }
        // 返回注册页
        return "register";
    }

    // 注销
    @GetMapping("/logout")
    public String toLogout(Model model) {
        result.setCode(100);
        result.setMsg("初始状态");
        result.setData(new Anonymous());
        model.addAttribute("result", result);
        model.addAttribute("categorys", categoryList);
        model.addAttribute("page", info);
        model.addAttribute("tid", tid);
        return "index";
    }

    // 商家管理后台页面 定向到商品管理页
    @GetMapping("/com")
    public String toCom(Model model, @RequestParam(value = "start", defaultValue = "0") int start) {//定向到商品管理页
//        System.out.println(result);
        model.addAttribute("result", result);
        // 页面的默认图片
        picname = "up.jpg";
        model.addAttribute("picname", picname);
        // 代码中start填0 和填1 的效果是一样的，都是显示第一页
        PageHelper.startPage(start, 3, "Pid DESC");
        List<Commodity> commodityList = mapper.queryComsAll();
        info = new PageInfo<>(commodityList);
        model.addAttribute("page", info);

        // 页面上的默认数据
        commodity = new Commodity();
        commodity.setPprice(Float.parseFloat("0.00"));
        commodity.setStocks(0);
        model.addAttribute("commodity", commodity);

        return "com";
    }

    // 上传并加载图片   上传到服务器
    @RequestMapping("/up")
    public String upload(Model model, HttpServletRequest request, @RequestParam("picfile") MultipartFile mulFile) throws IllegalStateException, IOException {
        if (!mulFile.isEmpty()) {
            String filename = mulFile.getOriginalFilename();
            File filepath = new File(uploadpath + File.separator + filename);
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            mulFile.transferTo(filepath);
            picname = filename;
            model.addAttribute("picname", picname);
        }
        model.addAttribute("result", result);
        model.addAttribute("page", info);
        model.addAttribute("commodity", commodity);

        return "com";
    }

    // 显示图片
    @RequestMapping("/show")
    public ResponseEntity showPicture(String mypic) {
        try {
            //由于是读取本机的文件，路径前面必须加上file:
//            System.out.println(File.separator);
            return ResponseEntity.ok(loader.getResource("file:" + uploadpath + File.separator + mypic));
        } catch (Exception e) {
            return ResponseEntity.notFound().build();
        }
    }


    // 增加商品
    @RequestMapping("/add")
    public String addCom(Model model, Commodity com) {
        model.addAttribute("result", result);
        model.addAttribute("picname", picname);
        //执行联动插入操作
        com.setScode(result.getData().getCode());//设置商家编码（来自当前登录商家的帐号）
        Commodityimage commodityimage = new Commodityimage();
        commodityimage.setPid(com.getPid());
        try {                                        //设置商品图片
            //  File.separator   ==>  \
            File file = new File(uploadpath + File.separator + picname);
            BufferedImage bufImage = ImageIO.read(file);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(bufImage, "jpg", stream);
            commodityimage.setImage(stream.toByteArray());//图片转换为字节数组(byte[])形式
        } catch (IOException e) {
            e.printStackTrace();
        }
        commodityimage.setCommodity(com);
        imgRepository.save(commodityimage);
        //回显结果
        commodity = comRepository.queryByPid(com.getPid());
        model.addAttribute("commodity", commodity);
        PageHelper.startPage(1, 3, "Pid DESC");
        List<Commodity> commodityList = mapper.queryComsAll();
        info = new PageInfo<>(commodityList);
        model.addAttribute("page", info);

        return "com";
    }


    @GetMapping("/cart")
    public String toCart(Model model) {//定向到购物车页
        model.addAttribute("result", result);
        System.out.println("result" + result);
        // 表示还没结算的商品
        preshopList = mapper.queryPresByUCode(result.getData().getCode());
        model.addAttribute("preshops", preshopList);

        System.out.println("preshoplist" + preshopList);
        // 表示已经结算的商品
        cfmShopList = mapper.queryCfmsByUCode(result.getData().getCode());
        model.addAttribute("cfmshops", cfmShopList);
        model.addAttribute("total", 0);
        model.addAttribute("msg", new Msg());

        return "cart";
    }

    @RequestMapping("/addtocart")
    public String addToCart(Model model, int pid) {
        mapper.insertComToPreshop(result.getData().getCode(), pid);

        model.addAttribute("result", result);
        model.addAttribute("categorys", categoryList);
        model.addAttribute("page", info);
        model.addAttribute("tid", tid);
//        aopService.activateUser((User) result.getData());

        return "index";
    }

    @RequestMapping("/changeconfirm")
    public String changeConfirm(Model model, int pid) {
        model.addAttribute("result", result);

        for (int i = 0; i < preshopList.size(); i++) {
            // get(i)  是list的方法
            if (preshopList.get(i).getPid() == pid) {
                // confirm是在购物车表中
                // 这里打勾和去掉打勾都会发送请求
                if (!preshopList.get(i).getConfirm()) {
                    preshopList.get(i).setConfirm(true);
                    System.out.println("打勾会发请求");

                } else {
                    preshopList.get(i).setConfirm(false);
                    System.out.println("去勾也会发请求");
                    break;
                }
            }
        }

        model.addAttribute("preshops", preshopList);
        // 已经付款的是不变的
        model.addAttribute("cfmshops", cfmShopList);
        float total = 0;

        for (int i = 0; i < preshopList.size(); i++) {
            if (preshopList.get(i).getConfirm()) {
                total += preshopList.get(i).getPprice() * preshopList.get(i).getCnum();
            }
        }
        model.addAttribute("total", total);
        model.addAttribute("msg", new Msg());

        return "cart";

    }

    @RequestMapping("/changecnum")
    public String changeCnum(Model model, int pid, int cnum) {
        model.addAttribute("result", result);
        for (int i = 0; i < preshopList.size(); i++) {
            if (preshopList.get(i).getPid() == pid) {
                preshopList.get(i).setCnum(cnum);
                break;
            }
        }
        model.addAttribute("preshops", preshopList);
        model.addAttribute("cfmshops", cfmShopList);

        float total = 0;
        for (int i = 0; i < preshopList.size(); i++) {
            if (preshopList.get(i).getConfirm()) {
                total += preshopList.get(i).getPprice() * preshopList.get(i).getCnum();

            }
        }
        model.addAttribute("total", total);
        model.addAttribute("msg", new Msg());

        return "cart";
    }

    @RequestMapping("/pay")
    public String payOrder(Model model) {
        model.addAttribute("result", result);
        orderService.payOrder(result.getData().getCode(), preshopList);
        preshopList = mapper.queryPresByUCode(result.getData().getCode());
        model.addAttribute("preshops", preshopList);
        cfmShopList = mapper.queryCfmsByUCode(result.getData().getCode());
        model.addAttribute("cfmshops", cfmShopList);
        model.addAttribute("total", 0);
        model.addAttribute("msg", new Msg());
//        aopService.activateUser((User) result.getData());

        return "cart";
    }


    // 留言板发送数据
    @RequestMapping("/msg")
    public String sendMsg(Model model, Msg msg) {
        if (msg.getText() != null && !msg.getText().equals("")) {
            msg.setText(msg.getText() + "&" + result.getData().getName());
            rabbitTemplate.send("买家留言", new Message(msg.getText().getBytes(StandardCharsets.UTF_8)));//留言内容封装为Message实体
            msg.setText("");
        }
        model.addAttribute("msg", msg);
        model.addAttribute("result", result);
        model.addAttribute("preshops", preshopList);
        model.addAttribute("cfmshops", cfmShopList);
        model.addAttribute("total", 0);

        return "cart";
    }

    // 接收显示留言
    @GetMapping("/board")
    public String toBoard(Model model) {//这个方法是必须的,页面链接通过它来定向到买家留言页
        model.addAttribute("result", result);
        // 消息队列
        String text = receiver.getText();
        System.out.println(text);
        if (text != null && !text.equals("")) {
            model.addAttribute("text", text.split("&")[0]);
            model.addAttribute("name", text.split("&")[1]);
        } else {
            model.addAttribute("text", "");
            model.addAttribute("name", "");
        }

        return "board";
    }


}
